package com.wyl.xyg.sample.web;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wyl.search.bean.SearchMessageBean;
import com.wyl.search.model.GeneralSearchService;
import com.wyl.search.sql.FormationSql;
import com.wyl.support.web.MessageHelper;
import com.wyl.xyg.sample.model.Appointment;
import com.wyl.xyg.sample.service.AppointmentServices;

import lombok.extern.slf4j.Slf4j;
/**
 * 这个是模板,开发参考用
 * @className: AppointmentController
 * @date: 2016年5月11日 上午9:38:28
 * @author sunkxu
 * @version 0.1
 * @since JDK 1.8
 */
@Controller
@ControllerAdvice
@Slf4j
public class AppointmentController{	
	//page 实际的页面   在Return用, controller内部用
	private final String NEW_OR_EIDT_PAGE = "/xyg/sample/newOrEdit";
	private final String LIST_PAGE = "/xyg/sample/list";
	
	//请求的链接地址 在 @RequestMapping(value = XXX) 用, 通常在页面调用
	private final String NEW_LINK = "/xyg/sample/new";
	private final String EDIT_LINK = "/xyg/sample/edit/{id}";
	
	private final String LIST_LINK = "/xyg/sample/list/{page}";
	private final String LIST_AJAX_LINK = "/xyg/sample/list/a/{page}";
	private final String LIST_FIRST_LINK = "/xyg/sample/list/1";
	
	//请求执行动作 在 @RequestMapping(value = XXX) 用,　在页面生成时用的动作
	private final String DEL_ACTION = "/xyg/sample/del";
	private final String SAVE_ACTION = "/xyg/sample/save";
	private final String UPDATE_ACTION = "/xyg/sample/update";
	

	
	@Autowired
	public AppointmentServices services;
	
	@Autowired
	private GeneralSearchService<Appointment> generalSearchService;
	
	@Autowired
	private SearchMessageBean searchMessageBean;
	
	@ModelAttribute("page")
    public String module() {
        return "sample";
    }
	

	//      OPTION    START
	@ModelAttribute("allStatus")
	public List<String> populateStatus() {
	    return Arrays.asList("新预约","办理中","已结束");
	}
	
	@ModelAttribute("allBusinessType")
	public List<String> populateBusinessType() {
	    return Arrays.asList("","信息系统","手机应用","信息网站","微信平台","其它");
	}	
	//  OPTION    END
	
	
	/**
	 *  List
	  * @Title: appointments
	  * @Description: TODO
	  * @param @param model
	  * @param @param page
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = LIST_LINK)
	public String appointments(Model model, @PathVariable("page") int page, HttpServletRequest request) {
		appointmentsList(model,page,request);
		return LIST_PAGE;
	}

	@RequestMapping(value = LIST_AJAX_LINK, method = RequestMethod.POST)
	public String appointmentsAjax(Model model, @PathVariable("page") int page, HttpServletRequest request) {
		appointmentsList(model,page,request);
		return LIST_PAGE + " :: dataList";
	}
	
	public void appointmentsList(Model model, int page, HttpServletRequest request) {
		searchMessageBean.setFormName("appointmentForm");
		searchMessageBean.setTargetDivName("dataList");	

		Map<String,String> requestParam = generalSearchService.getRequestParam(request);
		 
		searchMessageBean.setSql(FormationSql.buildSql(AppointmentServices.sql, requestParam));		 
		model.addAttribute("appointments", services.findAllAppointments(page, searchMessageBean.getSql()));		 
		model.addAttribute("paginationBean", generalSearchService.getPaginationBean(searchMessageBean, page, Appointment.class));
		model.addAttribute("params",requestParam);	
	}
	
	
	
	/**
	 *  Add　
	  * @Title: addAppointment
	  * @Description: TODO
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = NEW_LINK, method = RequestMethod.GET)
	public String addAppointment(Appointment appointment, Model model){
		model.addAttribute("action", SAVE_ACTION);
		return NEW_OR_EIDT_PAGE;
	}
	
	/**
	 *  Edit
	  * @Title: editAppointment
	  * @Description: TODO
	  * @param @param id
	  * @param @param model
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = EDIT_LINK, method = RequestMethod.GET)
	public String editAppointment(@PathVariable("id") long id, Model model){
		model.addAttribute("appointment", services.findById(id));
		model.addAttribute("action", UPDATE_ACTION);
		return NEW_OR_EIDT_PAGE;
	}
	
	/**
	 * 	Save
	  * @Title: saveOrUpdateAppointment
	  * @Description: TODO
	  * @param @param form
	  * @param @param errors
	  * @param @param ra
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = SAVE_ACTION, method = RequestMethod.POST)
	public String saveAppointment(@Valid @ModelAttribute Appointment form, Errors errors, Model model, RedirectAttributes ra) {
		if (errors.hasErrors()) {
			model.addAttribute("action", SAVE_ACTION);
			return NEW_OR_EIDT_PAGE;
		}
		//设置Appid
		/*form.setAppid(UserService.getAppid());*/
		services.save(form);
        // see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
        MessageHelper.addSuccessAttribute(ra, "add.success");
        
		return "redirect:"+LIST_FIRST_LINK;
	}
	
	/**
	 *  Update
	  * @Title: updateAppointment
	  * @Description: TODO
	  * @param @param form
	  * @param @param errors
	  * @param @param ra
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = UPDATE_ACTION, method = RequestMethod.POST)
	public String updateAppointment(@Valid @ModelAttribute Appointment form, Errors errors, Model model, RedirectAttributes ra) {
		if (errors.hasErrors()) {
			model.addAttribute("action", UPDATE_ACTION);
			return NEW_OR_EIDT_PAGE;
		}
		services.update(form);
		log.debug("updateAppointment form.businessType {}", form.businessType);
        MessageHelper.addSuccessAttribute(ra, "update.success");
        
		return "redirect:"+LIST_FIRST_LINK;
	}
	
	/**
	 *  删除
	  * @Title: delAppointment
	  * @Description: TODO
	  * @param @param request
	  * @param @return    设定文件
	  * @return String    返回类型
	  * @throws
	 */
	@RequestMapping(value = DEL_ACTION, method = RequestMethod.POST)
	public String delAppointment(HttpServletRequest request, Model model, RedirectAttributes ra) {
		try{
			String[] chks = request.getParameterValues("chk");		
			int recordCount = services.delAppointmentsById(chks);			
			MessageHelper.addSuccessAttribute(ra, "del.success", new Object[] {recordCount});
		}catch(Exception e){
			e.printStackTrace();
			MessageHelper.addErrorAttribute(ra, "del.error");
		}
        // see /WEB-INF/i18n/messages.properties and /WEB-INF/views/homeSignedIn.html
                
		return "redirect:"+LIST_FIRST_LINK;
	}
	
	
}

